// pages/questions/do/do.js
const app = getApp();
const utils = require('../../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    answer_show: false,
    question_active: 0,
    questions: [],
    left: 0,
    answer_correct: [],
    tips: false,
    collection: '../../../common/static/images/hc_icon_sc1.png',
    disabled: false,
    submissionBtn: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    let id = options.id;
    _this.setData({
      id: id
    })
    utils.requests({
      url: 'questions/answer/'+id,
      success:function(data){
        _this.setData({
          questions: data.data.data
        })
        for ( let i = 0; i < data.data.data.answer.length; i++ ) {
          let keyname = 'answer_correct['+i+']';
          _this.setData({
            [keyname]: []
          })
          let keynames = 'answer_correct['+i+'].key';
          let keyname1 = 'answer_correct['+i+'].is_answer';
          let xuan = 'answer_correct['+i+'].xuan';
          _this.setData({
            [keynames]: [],
            [keyname1]: '',
            [xuan]: []
          });
        }
        let answer = wx.getStorageSync('answer_'+id);
        if ( answer ) {
          _this.setData({
            answer_correct: answer
          })
        } else {
          utils.requests({
            url: 'questions/doAnswer/'+id,
            success:function(e){
              let answer_correct = [];
              for ( let key in data.data.data.answer ) {
                let _question = data.data.data.answer[key];
                for ( let k in e.data.data ) {
                  if ( _question.id == e.data.data[k].aid ) {
                    if ( !answer_correct[key] ) {
                      answer_correct[key] = {};
                      answer_correct[key].key = [];
                      answer_correct[key].is_answer = '';
                      answer_correct[key].xuan = [];
                    }
                    let is_answer = 0;
                    let is_answers = '';
                    let sucCount = 0;
                    for ( let item in _question.opt ) {
                      if ( _question.opt[item].id == e.data.data[k].oid ) {
                        answer_correct[key].key.push(item);
                        answer_correct[key].xuan[item] = e.data.data[k].correct == 0?'xuan':'answer';
                      }
                      if ( e.data.data[k].correct == 1 ) {
                        is_answer++;
                      } else {
                        is_answers = false;
                      }
                      if ( _question.opt[item].is_answer == 1 ) {
                        sucCount++;
                      }
                    }
                    if ( is_answers !== false && is_answer == sucCount ) {
                      is_answers = true;
                    }
                    answer_correct[key].is_answer = is_answers;
                  }
                }
              }
              _this.setData({
                answer_correct: answer_correct
              })
            }
          }) 
        }
        utils.requests({
          url: 'questions/collection/get/'+_this.data.questions.answer[0].id,
          success: function(data){
            console.log(data);
          },
          complete: function(data){
            if ( data.data.code == 200 ) {
              _this.setData({
                collection: '../../../common/static/images/hc_icon_sc.png'
              })
            } else {
              _this.setData({
                collection: '../../../common/static/images/hc_icon_sc1.png'
              })
            }
          }
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 答题卡显示|隐藏
  answerShow: function(){
    let _this = this;
    _this.setData({
      answer_show: !_this.data.answer_show
    })
  },

  touchStart: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        startX: e.touches[0].clientX
      });
    }
  },

  touchMove: function(e){
    let _this = this;
    if (e.touches.length == 1) {
      let moveX = e.touches[0].clientX;
      let diffX = _this.data.startX - moveX;
      if (diffX < 0) { //向右
        _this.setData({
          left: 1
        })
      } else if (diffX > 0) { //向左
        _this.setData({
          left: 2
        })
      }
    }
  },
  touchEnd: function (e) {
    let _this = this;
    let maxKey = _this.data.questions.answer.length;
    let current = _this.data.left==1?
      _this.data.question_active-1:
      (_this.data.left==2?_this.data.question_active+1:false);
    if ( current !== false ) {
      if ( current >= maxKey ) {
        _this.setData({
          question_active: 0
        })
      } else if ( current < 0 ) {
        _this.setData({
          question_active: maxKey-1
        })
      } else {
        _this.setData({
          question_active: current
        })
      }
    }
    _this.setData({
      left: 0
    });
    utils.requests({
      url: 'questions/collection/get/'+_this.data.questions.answer[_this.data.question_active].id,
      success: function(data){
        
      },
      complete: function(data){
        if ( data.data.code == 200 ) {
          _this.setData({
            collection: '../../../common/static/images/hc_icon_sc.png'
          })
        } else if(data.data.code == 404) {
          _this.setData({
            collection: '../../../common/static/images/hc_icon_sc1.png'
          })
        } else {
          wx.showToast({
            title: data.data.message,
            icon: 'none',
            duration: 1500
          })
        }
      }
    })
  },

  // 选择题
  choice: function(e){
    let _this = this;
    let data = e.currentTarget.dataset;
    let answer = _this.data.questions.answer[_this.data.question_active];
    let opt = answer.opt[data.key];
    let answer_correct = _this.data.answer_correct;
    if ( answer_correct[_this.data.question_active] && (answer_correct[_this.data.question_active].is_answer === true || answer_correct[_this.data.question_active].is_answer === false || answer_correct[_this.data.question_active].key.indexOf(data.key) >= 0) ) {
      return false;
    }
    let is_answer = false;
    let keys = answer_correct[_this.data.question_active]?answer_correct[_this.data.question_active].key:[];
    let key = 'answer_correct['+_this.data.question_active+'].key';
    keys.push(data.key);
    let xuan = [];
    for ( let key in keys ) {
      xuan[keys[key]] = answer.opt[keys[key]].is_answer == 1?'answer':'xuan'
    }
    let xuans = 'answer_correct['+_this.data.question_active+'].xuan'
    if ( answer.type == 1 ) {
      if ( opt.is_answer == 1 ) {
        is_answer = true;
      }
    } else if ( answer.type == 2 ) {
      let opts = answer.opt;
      if ( opt.is_answer == 0 ) {
        is_answer = false;
      } else {
        let res = 0;
        let succount = 0 
        for ( let key in opts ) {
          if ( opts[key].is_answer == 1 ) {
            succount++;
          }
          for ( let k in keys ) {
            if ( opts[key].is_answer == 1 && key == keys[k] ) {
              res++;
            }
          }
        }
        if ( res < succount ) {
          _this.setData({
            [key]: keys,
            [xuans]: xuan
          })
          wx.setStorageSync('answer_'+_this.data.id, _this.data.answer_correct);
          return false;
        } else {
          is_answer = true;
        }
      }
    }
    let is_answers = 'answer_correct['+_this.data.question_active+'].is_answer';
    _this.setData({
      [key]: keys,
      [is_answers]: is_answer,
      [xuans]: xuan
    })
    wx.setStorageSync('answer_'+_this.data.id, _this.data.answer_correct);
  },

  // 提交结果
  submission: function( e ) {
    let _this = this;
    _this.setData({
      answer_show: false
    })
    for ( let key in _this.data.answer_correct ) {
      if ( !_this.data.answer_correct[key] || ( _this.data.answer_correct[key].is_answer !== true && _this.data.answer_correct[key].is_answer !== false) ) {
        _this.setData({
          tips: true
        })
        return false;
      }
    }
    subAnswer(_this);
  },

  //强制提交
  submissionBtn: function()
  {
    let _this = this;
    _this.setData({
      answer_show: false,
      submissionBtn: true
    })
    subAnswer(_this);
  },

  // 取消提交试卷
  cencalSubmit: function(){
    this.setData({
      tips: false
    })
  },

  // 收藏题目
  collection: function(){
    let _this = this;
    if ( _this.data.disabled === true ) {
      return false;
    }
    _this.setData({
      disabled: true
    });
    let aid = _this.data.questions.answer[_this.data.question_active].id;
    utils.requests({
      url:'questions/collection/collection/'+aid,
      success:function(data){
        if ( data.data.code == 200 ) {
          if ( _this.data.collection === '../../../common/static/images/hc_icon_sc1.png' ) {
            _this.setData({
              collection: '../../../common/static/images/hc_icon_sc.png'
            })
          } else {
            _this.setData({
              collection: '../../../common/static/images/hc_icon_sc1.png'
            })
          }
        } else {
          wx.showToast({
            title: data.data.message,
            icon: 'none',
            duration: 1500
          })
        }
      },
      complete: function(){
        _this.setData({
          disabled: false
        });
      }
    });
  }

})

// 提交试题
let subAnswer = (_this) => {
  let answer_correct = _this.data.answer_correct;
  let questions = _this.data.questions;
  let data = {};
  data.qid = _this.data.id;
  let list = [];
  for ( let key in answer_correct ) {
    list[key] = {};
    list[key].aid = questions.answer[key].id;
    let oid = [];
    for ( let k in answer_correct[key].key ) {
      oid[k] = {};
      oid[k].oid = questions.answer[key].opt[answer_correct[key].key[k]].id;
      oid[k].correct = questions.answer[key].opt[answer_correct[key].key[k]].is_answer;
    }
    list[key].answer = oid;
  }
  data.list = list;
  utils.requests({
    url: 'questions/submission',
    method: 'POST',
    data:data,
    success:function(data){
      if ( data.data.code == 200 ) {
        wx.showToast({
          title: '已提交',
          duration: 1500
        })
      } else {
        _this.setData({
          submissionBtn: false
        })
      }
    }
  })
} 